package edu.pku.sei.sct.primitives;

import java.util.Set;

import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EObject;

import edu.pku.sei.AMT.LinkConstraint;
import edu.pku.sei.AMT.ObjectVariable;
import edu.pku.sei.AMT.Rule;
import edu.pku.sei.AMT.Section;
import edu.pku.sei.ocl.evaluation.Environment;
import edu.pku.sei.ocl.evaluation.OCLVariable;
import edu.pku.sei.ocl.utilities.OCLStandardLibrary;
import edu.pku.sei.sct.evaluation.RuleContext;
import edu.pku.sei.sct.evaluation.SCTEnvironment;

public class IsContextValid extends AbstractPrimitive {
	static final public String ID = "IsContextValid";
	
	public IsContextValid(SCTEnvironment e) {
		super(e);
	}

	@Override
	public Object execute(Object... argv) {
		
		RuleContext rc = (RuleContext)argv[0];
		Rule rule = rc.getRule();

		EList vars = rule.getVariables();
		
		for(Object v : vars) {
			if(v instanceof ObjectVariable) {
				Object value = rc.getValue(((ObjectVariable)v).getName());
				if(OCLStandardLibrary.oclIsValid(value)) {
					if(value instanceof EObject) {
						if(Environment.log.oclIsDelete((EObject)value))
							return false;
					}
				}
			}
		}
		
		EList secs = rule.getSections();
		
		for(Object o : secs) {
			Section s = (Section)o;
			EList links = s.getLinks();
			
			for(Object l : links) {
				LinkConstraint lc = (LinkConstraint)l;
				Object src = rc.getValue(lc.getSource().getName());
				Object tar = rc.getValue(lc.getTarget().getName());
				if(OCLStandardLibrary.oclIsValid(src) && OCLStandardLibrary.oclIsValid(tar)) {
					if(Environment.log.oclIsDelete((EObject)src, (EObject)tar, 
							this.getSctEnvironment().getReference(lc.getSource().getScope(), lc.getSource().getType(), lc.getRefName())))
						return false;
				}
			}
		}
		
		
		return true;
	}

	@Override
	public String getID() {
		// TODO Auto-generated method stub
		return ID;
	}

}
